package cc.sunni.article.controller;

import cc.sunni.api.BaseController;
import cc.sunni.api.controller.article.ArticlePortalControllerApi;
import cc.sunni.api.controller.user.UserControllerApi;
import cc.sunni.api.utils.PageUtils;
import cc.sunni.article.service.ArticlePortalService;
import cc.sunni.common.Constant;
import cc.sunni.common.utils.IPUtil;
import cc.sunni.common.utils.R;
import cc.sunni.pojo.Article;
import cc.sunni.pojo.vo.AppUserVO;
import cc.sunni.pojo.vo.ArticleDetailVO;
import cc.sunni.pojo.vo.IndexArticleVO;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
public class ArticlePortalController extends BaseController implements ArticlePortalControllerApi {
    @Autowired
    private ArticlePortalService articlePortalService;
    @Autowired
    private UserControllerApi userControllerApi;

    @Override
    public R list(String keyword, Integer category, Integer page, Integer pageSize) {

        PageUtils gridResult = articlePortalService.queryIndexArticleList(keyword, category, page, pageSize);
// START

        /*List<Article> list = (List<Article>)gridResult.getRows();

        // 1. 构建发布者id列表
        Set<String> idSet = new HashSet<>();
        for (Article a : list) {
//            System.out.println(a.getPublishUserId());
            idSet.add(a.getPublishUserId());
        }
        System.out.println(idSet.toString());

        // 2. 发起远程调用（restTemplate），请求用户服务获得用户（idSet 发布者）的列表
        String userServerUrlExecute
                = "http://user.imoocnews.com:8003/user/queryByIds?userIds=" + JsonUtils.objectToJson(idSet);
        ResponseEntity<R> responseEntity
                = restTemplate.getForEntity(userServerUrlExecute, R.class);
        R bodyResult = responseEntity.getBody();
        List<AppUserVO> publisherList = null;
        if (bodyResult.getStatus() == 200) {
            String userJson = JsonUtils.objectToJson(bodyResult.getData());
            publisherList = JsonUtils.jsonToList(userJson, AppUserVO.class);
        }
//        for (AppUserVO u : publisherList) {
//            System.out.println(u.toString());
//        }

        // 3. 拼接两个list，重组文章列表
        List<IndexArticleVO> indexArticleList = new ArrayList<>();
        for (Article a : list) {
            IndexArticleVO indexArticleVO = new IndexArticleVO();
            BeanUtils.copyProperties(a, indexArticleVO);

            // 3.1 从publisherList中获得发布者的基本信息
            AppUserVO publisher  = getUserIfPublisher(a.getPublishUserId(), publisherList);
            indexArticleVO.setPublisherVO(publisher);
            indexArticleList.add(indexArticleVO);
        }
        gridResult.setRows(indexArticleList);*/
// END
        gridResult = rebuildArticleGrid(gridResult);
        return R.ok(gridResult);
    }

    private PageUtils rebuildArticleGrid(PageUtils gridResult) {
        // START

        List<Article> list = (List<Article>) gridResult.getRows();

        // 1. 构建发布者id列表
        Set<String> idSet = new HashSet<>();
        List<String> idList = new ArrayList<>();
        for (Article a : list) {
//            System.out.println(a.getPublishUserId());
            // 1.1 构建发布者的set
            idSet.add(a.getPublishUserId());
            // 1.2 构建文章id的list
            idList.add(Constant.REDIS_ARTICLE_READ_COUNTS + ":" + a.getId());
        }
        System.out.println(idSet.toString());
        // 发起redis的mget批量查询api，获得对应的值
        List<String> readCountsRedisList = redis.mget(idList);

        // 2. 发起远程调用（restTemplate），请求用户服务获得用户（idSet 发布者）的列表
//        String userServerUrlExecute
//                = "http://user.imoocnews.com:8003/user/queryByIds?userIds=" + JsonUtils.objectToJson(idSet);
//        ResponseEntity<R> responseEntity
//                = restTemplate.getForEntity(userServerUrlExecute, R.class);
//        R bodyResult = responseEntity.getBody();
//        List<AppUserVO> publisherList = null;
//        if (bodyResult.getStatus() == 200) {
//            String userJson = JsonUtils.objectToJson(bodyResult.getData());
//            publisherList = JsonUtils.jsonToList(userJson, AppUserVO.class);
//        }
        List<AppUserVO> publisherList = getPublisherList(idSet);
//        for (AppUserVO u : publisherList) {
//            System.out.println(u.toString());
//        }

        // 3. 拼接两个list，重组文章列表
        List<IndexArticleVO> indexArticleList = new ArrayList<>();
//        for (Article a : list) {
//            IndexArticleVO indexArticleVO = new IndexArticleVO();
//            BeanUtils.copyProperties(a, indexArticleVO);
//
//            // 3.1 从publisherList中获得发布者的基本信息
//            AppUserVO publisher  = getUserIfPublisher(a.getPublishUserId(), publisherList);
//            indexArticleVO.setPublisherVO(publisher);
//
//            // 3.2 重新组装设置文章列表中的阅读量
//            int readCounts = getCountsFromRedis(REDIS_ARTICLE_READ_COUNTS + ":" + a.getId());
//            indexArticleVO.setReadCounts(readCounts);
//
//            indexArticleList.add(indexArticleVO);
//        }
        for (int i = 0; i < list.size(); i++) {
            IndexArticleVO indexArticleVO = new IndexArticleVO();
            Article a = list.get(i);
            BeanUtils.copyProperties(a, indexArticleVO);

            // 3.1 从publisherList中获得发布者的基本信息
            AppUserVO publisher = getUserIfPublisher(a.getPublishUserId(), publisherList);
            indexArticleVO.setPublisherVO(publisher);

            // 3.2 重新组装设置文章列表中的阅读量
            String redisCountsStr = readCountsRedisList.get(i);
            int readCounts = 0;
            if (StringUtils.isNotBlank(redisCountsStr)) {
                readCounts = Integer.parseInt(redisCountsStr);
            }
            indexArticleVO.setReadCounts(readCounts);

            indexArticleList.add(indexArticleVO);
        }


        gridResult.setRows(indexArticleList);
// END
        return gridResult;
    }

    private AppUserVO getUserIfPublisher(String publisherId,
                                         List<AppUserVO> publisherList) {
        for (AppUserVO user : publisherList) {
            if (user.getId().equalsIgnoreCase(publisherId)) {
                return user;
            }
        }
        return null;
    }

    // 发起远程调用，获得用户的基本信息
    private List<AppUserVO> getPublisherList(Set<String> idSet) {
//        String userServerUrlExecute = "http://user.imoocnews.com:8003/user/queryByIds?userIds=" + JSONUtil.toJsonStr(idSet);
//        String respone = HttpUtil.get(userServerUrlExecute);
//        R bodyResult = JSONUtil.toBean(respone, R.class);

        R bodyResult = userControllerApi.queryByIds(JSONUtil.toJsonStr(idSet));
        List<AppUserVO> publisherList = null;
        if ((Integer) bodyResult.get("status") == 200) {
            String userJson = JSONUtil.toJsonStr(bodyResult.get("data"));
            publisherList = JSONUtil.toList(userJson, AppUserVO.class);
        }
        return publisherList;
    }

    @Override
    public R hotList() {
        return R.ok(articlePortalService.queryHotList());
    }

    @Override
    public R queryArticleListOfWriter(String writerId, Integer page, Integer pageSize) {
        PageUtils gridResult = articlePortalService.queryArticleListOfWriter(writerId, page, pageSize);
        gridResult = rebuildArticleGrid(gridResult);
        return R.ok(gridResult);
    }

    @Override
    public R queryGoodArticleListOfWriter(String writerId) {
        PageUtils gridResult = articlePortalService.queryGoodArticleListOfWriter(writerId);
        return R.ok(gridResult);
    }

    @Override
    public R detail(String articleId) {
        ArticleDetailVO detailVO = articlePortalService.queryDetail(articleId);
//        Set<String> idSet = new HashSet<>();
//        idSet.add(detailVO.getPublishUserId());
//        List<AppUserVO> publisherList = getPublisherList(idSet);
//        if (CollectionUtil.isNotEmpty(publisherList)) {
//            detailVO.setPublishUserName(publisherList.get(0).getNickname());
//        }
//        detailVO.setReadCounts(getCountsFromRedis(Constant.REDIS_ARTICLE_READ_COUNTS + ":" + articleId));
        return R.ok(detailVO);
    }

    @Override
    public R readArticle(String articleId, HttpServletRequest request) {
        String userIp = IPUtil.getRequestIp(request);
        // 设置针对当前用户ip的永久存在的key，存入到redis，表示该ip的用户已经阅读过了，无法累加阅读量
        redis.setnx(Constant.REDIS_ALREADY_READ + ":" + articleId + ":" + userIp, userIp);
        redis.increment(Constant.REDIS_ARTICLE_READ_COUNTS + ":" + articleId, 1);
        return R.ok();
    }

    @Override
    public Integer readCounts(String articleId) {
        return getCountsFromRedis(Constant.REDIS_ARTICLE_READ_COUNTS + ":" + articleId);
    }
}
